import socket
import threading

import time





def hook(hd):
    while 1:
        name = input("CMD:")
        print('sending: ' + name)
        hd.send(name.encode(encoding="utf-8"))


def tcplink(sock, addr):
    print('Accept new connection from %s:%s...' % addr)
    sock.send(b'whoami\n')

    sender = threading.Thread(target=hook, args=[sock])
    sender.start()

    while True:
        data = sock.recv(1024)
        time.sleep(1)
        if not data or data.decode('utf-8') == 'exit':
            break
        print(data.decode('utf-8'))
        # sock.send(b'whoami')
    sock.close()
    print('Connection from %s:%s closed.' % addr)


if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument('-p', dest='port', help='port')
    parser.add_argument('-a', dest='admin', action="store_true")
    args = parser.parse_args()
    assert args.port is not None

    if args.admin:
        ""
    else:

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        s.bind(('0.0.0.0', int(args.port)))
        s.listen(2)

        while True:
            # 接受一个新连接 :
            sock, addr = s.accept()
            # 创建新线程来处理TCP连接:
            t = threading.Thread(target=tcplink, args=(sock, addr))
            t.start()
